<template>
  <div class="app-container">
    <el-card v-if="activites" style="height: 650px">
      <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch"
               label-width="68px" style="display: flex; justify-content: flex-end;">

        <el-form-item label="日期" prop="activityDate">
          <el-date-picker
            v-model="queryParams.dateTime"
            type="datetimerange"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
          <!--        <el-input-->
          <!--          v-model=""-->
          <!--          placeholder="请输入活动日期"-->
          <!--          clearable-->
          <!--          @keyup.enter.native="handleQuery"-->
          <!--        />-->
        </el-form-item>
        <el-form-item label="名称" prop="activityName">
          <el-input
            v-model="queryParams.activityName"
            placeholder="请输入活动名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">

      </el-row>

      <el-table :data="activitiesList" stripe @selection-change="handleSelectionChange" >
        <el-table-column label="公寓名称" align="center" prop="apartmentName" fixed show-overflow-tooltip/>
        <el-table-column label="活动名称" align="center" prop="activityName" fixed />
        <el-table-column label="活动时间" align="center" prop="activityDate" fixed />
        <el-table-column label="活动负责人" align="center" prop="leaderName" fixed />
        <el-table-column label="备注" align="center" prop="notes" fixed />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

    </el-card>

    <activity-details v-if="activityDetails" :formData="formData" @return-value="handleValue"></activity-details>

  </div>
</template>

<script>
  import {
    listActivities,
    getActivities,
    delActivities,
    addActivities,
    updateActivities,
    updateActivitiesVideo, getActivitiesVideo
  } from "@/api/business/activities";
  import {fileUpload, getElderApartment} from "@/api/business/elderInfo";
  import {getMemberInfoList} from "@/api/business/memberInfo";
  import activityDetails from "@/views/business/activityRecoreds/activityDetails";

  export default {
    components:{
      activityDetails
    },
    data() {
      return {
        activityDetails:false,
        activites:true,
        formData:{},
        videoUrl:"",
        dialogVisible: false,
        titleName:"",
        videoList : {},
        drawer: false,
        //从右侧打开
        direction: 'rtl',
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 公寓活动表格数据
        activitiesList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        openUpload:false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          dateTime:null,
          activityDate: null,
          activityTime: null,
          activityName: null,
          leaderName: null,
        },
        // 表单参数
        form: {},
        memberList:{},
        apartmentList:{},
        // 表单校验
        rules: {
          apartmentId: [
            { required: true, message: "公寓不能为空", trigger: "blur" }
          ],
          activityDate: [
            { required: true, message: "活动日期不能为空", trigger: "blur" }
          ],
          activityName: [
            { required: true, message: "活动名称不能为空", trigger: "blur" }
          ],
        },
        user:{},
      };
    },
    created() {
      this.getList();
      this.getElderApartmentInfo();
      this.getMemberInfoList();
      this.user = this.$store.state.user;
    },
    methods: {
      /** 查询公寓活动列表 */
      getList() {
        this.loading = true;
        if(this.queryParams.dateTime != null) {
          const time = this.queryParams.dateTime;
          this.queryParams.startTime = time[0];
          this.queryParams.endTime = time[1]
        }
        listActivities(this.queryParams).then(response => {
          console.log(response.rows);
          this.activitiesList = response.rows;
          this.total = response.total;
          this.loading = false;
        }).catch(error =>{
          console.error(error);
        });

      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 取消按钮
      cancelUPVideo() {
        this.openUpload = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          activityId: null,
          apartmentId: null,
          activityDate: null,
          activityTime: null,
          activityName: null,
          activityUrl : null,
          activityDescription: null,
          applyStatus: null,
          leaderName: null,
          leaderId: null,
          participantCount: null,
          notes: null,
          createUserId: null,
          createTime: null,
          updateUserId: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.activityId)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加公寓活动";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const activityId = row.activityId
        getActivities(activityId).then(response => {
          this.form = response.data;
          this.formData = response.data;
          this.activites = false;
          this.activityDetails = true;
          console.log(this.formData)

          // this.open = true;
          // this.title = "修改公寓活动";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.activityId != null) {
              this.form.updateUserId = this.user.id;
              updateActivities(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.createUserId = this.user.id;
              addActivities(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      submitActivitiesVideo(){
        this.$refs["form"].validate(valid => {
          if (valid) {
            updateActivitiesVideo(this.form).then(response => {
              this.$modal.msgSuccess("添加成功");
              this.openUpload = false;
              // this.open = false;
              this.getList();
            });
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const activityIds = row.activityId
        this.$modal.confirm('是否确认删除公寓活动编号为"' + activityIds + '"的数据项？').then(function() {
          return delActivities(activityIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('business/activities/export', {
          ...this.queryParams
        }, `activities_${new Date().getTime()}.xlsx`)
      },
      getElderApartmentInfo(){
        getElderApartment().then(response =>{
          this.apartmentList = response.rows
        })
      },
      getMemberInfoList(){
        getMemberInfoList().then(response =>{
          this.memberList = response.data;
          console.log(this.memberList);
        })
      },
      //活动视频上传弹出页面
      handleVideoUpload(row){
        this.form = row;
        this.openUpload = true;
        this.title = "活动视频上传";
      },
      //** 查看活动视频
      checkActVideo(row){
        // this.drawer = true
        const act = {activityId:row.activityId}
        //获取该活动下的视频内容
        getActivitiesVideo(act).then(response => {
          this.videoList = response.data;
          this.form.activityUrl = response.data.activityUrl;
          if(this.form.activityUrl == null){
            this.$message({
              message: '该活动暂未上传视频',
              type: 'warning'
            });
            return;
          }
          window.open(this.form.activityUrl);
          // this.openNewUrl(this.form.activityUrl);
          console.log(this.videoList);
          console.log(this.form.activityUrl);
        });
      },
      openNewUrl(url){
        let path=window.location.protocol+'//'+url
        window.location.href=path
      },
      beforeUpload(file) {
        // 处理上传文件之前的逻辑，例如限制文件类型和大小等
        // ...省略相关代码...
        console.log(file)
        return true; // 返回 true 以继续上传文件
      },
      //文件上传
      handleUpload() {
        const uploadComponent = this.$refs.upload; // 引用上传组件
        const file = uploadComponent.uploadFiles[0]; // 获取选择的文件
        if (file) {
          // 构造 FormData 对象并添加文件参数
          const formData = new FormData();
          formData.append('file', file.raw); // 添加文件参数，注意使用 file.raw 获取原始文件对象
          //调用接口
          console.log(formData);
          fileUpload(formData).then(response => {
            // 处理响应结果
            this.form.activityUrl = response;
            this.$modal.msgSuccess("上传成功!");
            console.log(response)
          }).catch(error => {
            // 处理错误
            this.$modal.msgError("上传失败!");
          });
        } else {
          // 处理未选择文件的情况
          this.$modal.msgWarning("请选择文件后上传");
        }
      },
      playVideo(url){
        this.dialogVisible = true;
        this.videoUrl = url;
      },
      handleValue(){
        this.activityDetails = false;
        this.activites = true;
        this.getList();
      }
    }
  };
</script>
